package com.bk.bookviews.service.impl;

import com.bk.bookviews.common.Pagination;
import com.bk.bookviews.domain.Notice;
import com.bk.bookviews.domain.NoticeExample;
import com.bk.bookviews.domain.UserInfo;
import com.bk.bookviews.exception.BusinessException;
import com.bk.bookviews.exception.BusinessExceptionEnum;
import com.bk.bookviews.mapper.NoticeMapper;
import com.bk.bookviews.service.NoticeService;
import com.bk.bookviews.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class NoticeServiceImpl implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Notice selectNotice(Integer id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveNotice(Notice notice, String token) {
        UserInfo userInfo = (UserInfo) redisUtil.get(token);
        if (userInfo == null){
            throw new BusinessException(BusinessExceptionEnum.LOGON_FAILURE);
        }
        notice.setCreateId(userInfo.getUserId());
        notice.setCreateTime(new Date());
        noticeMapper.insertSelective(notice);
    }

    @Override
    public Pagination selectNoticeList(Notice notice) {
        NoticeExample example = new NoticeExample();
        NoticeExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(notice.getTitle())){
            criteria.andTitleLike("%"+notice.getTitle()+"%");
        }
        if (StringUtils.isNotBlank(notice.getContent())){
            criteria.andContentLike("%"+notice.getContent()+"%");
        }
        return new Pagination(noticeMapper.selectByExample(example));
    }

    @Override
    public void delete(Integer id) {
        noticeMapper.deleteByPrimaryKey(id);
    }
}
